<template>
    <div class="occupancy">
        <div class="row">
            <div class="col-md-12">
                <div class="panel">
                    <div style="padding: 20px;">
                        <h4>Available room</h4>
                        <div class="row">
                            <div class="col-md-6">
                                <label>Begin Date</label>
                                <input v-model="dateBegin" class="form-control" type="date"/>
                            </div>
                            <div class="col-md-6">
                                <label>End Date</label>
                                <input v-model="dateEnd" class="form-control" type="date"/>
                            </div>
                        </div>
                        <div class="row" style="overflow: hidden;">
                            <button class="btn btn-info pull-right" type="button" @click="availableRoom"
                                    style="margin:10px;">
                                查空房
                            </button>
                        </div>
                        <div class="row">
                            all room (using ical only)
                            <input class="form-control" type="text" placeholder="" readonly="readonly"/>
                            <button class="btn btn-info pull-right" type="button" @click="allRoomIcalOnly"
                                    style="margin-top: 10px;">
                                查入住率
                            </button>
                        </div>
                    </div>

                </div>
            </div>


        </div>
        <div class="row">
            <div class="col-md-12">
                <filter-form :columns="filterColumns" @submit="submit"></filter-form>
            </div>
        </div>
        <div class="row">
            <div class="col-md-12">
                <item-table  title="Physical Room List" :columns="columns" :data="data" :loading="tableLoading" @sort="sort"
                            :total="data.length" model="occupancy"
                >
                    <template slot="physical_room_id" slot-scope="props">
                        <a :href="`#/physicalroomcalendar/${props.item.physical_room_id}`" target="_blank">
                            {{props.item.physical_room_id}}
                        </a>
                    </template>
                </item-table>
            </div>
        </div>
    </div>
</template>

<script>
    import {queryTable} from "@/api/stat";
    import {toJsonData} from "@/utils";

    import ItemTable from '@/components/widgets/ItemTable'
    import ItemDetail from '@/components/widgets/ItemDetail'
    import FilterForm from '@/components/widgets/FilterForm'

    export default {
        name: "Occupany",
        components: {ItemTable, ItemDetail, FilterForm},
        created() {
            this.orderField = []
        },
        data() {
            return {
                tableLoading: false,
                dateBegin: '',
                dateEnd: '',
                fixedColumns: [
                    {'label': 'all', 'value': 'all', 'inputType': 'text'},
                    {'label': 'physical_room_id', 'value': 'physical_room_id', 'inputType': 'text'},
                    {'label': 'host_name', 'value': 'host_name', 'inputType': 'text'},
                    {'label': 'max_guest_num', 'value': 'max_guest_num', 'inputType': 'numberRange'},
                    {'label': 'location', 'value': 'location', 'inputType': 'text'},
                    {'label': 'room_area', 'value': 'room_area', 'inputType': 'text'},
                    {'label': 'room_type', 'value': 'room_type', 'inputType': 'text'},
                ],
                filterColumns: [],

                filters: [],

                model: 'Occupancy',

                //data
                table: null,
                originalData: [],
                data: [],
            }
        },
        computed: {
            columns() {
                if (!this.table) {
                    return []
                }

                let tmp = []
                this.filterColumns = [].concat(this.fixedColumns)

                this.table.headers.forEach(item => {
                    let sort = this.orderField.indexOf(item) !== -1 ? true : false
                    tmp.push({
                        label: item,
                        key: item,
                        sort
                    })

                    if (item.indexOf('checkin_ratio') !== -1) {
                        this.filterColumns.push(
                            {'label': item, 'value': item, 'inputType': 'numberRange'},
                        )
                    }

                })
                return tmp
            }

        },
        methods: {
            availableRoom() {
                this.fetch('available_room', {
                    'begin_date': this.dateBegin,
                    'end_date': this.dateEnd
                })
            },
            allRoomIcalOnly() {
                this.fetch('all_room_ical_only')
            },
            fetch(note, attr) {
                if (!this.tableLoading) {
                    this.tableLoading = true
                    queryTable('occupancy', note, attr)
                        .then((response) => {
                            this.table = response.data
                            this.tableLoading = false
                            this.originalData = toJsonData(response.data.headers, response.data.data)
                            this.filter()

                            if (note == 'all_room_ical_only') {
                                this.preprocess()
                            }

                        })
                        .catch((error) => {
                            this.tableLoading = false
                            this.error = error.toString()
                        })
                } else {
                    $.toast({
                        heading: 'Please wait',
                        text: 'waiting!',
                        position: 'top-right',
                        loaderBg: '#ff6849',
                        icon: 'error',
                    });
                }
            },
            sort() {
            },
            submit(opt) {
                this.filters = opt.filters
                this.filter()
            },
            preprocess() {
                for (let i = 0; i < this.originalData.length; i++) {
                      let item = this.originalData[i]
                      for (let key in item) {
                          if (key.indexOf('checkin_ratio') != -1) {
                              item[key] = (item[key] * 100).toFixed(2) + '%'
                          }
                      }
                }
            },
            filter() {
                let isFilterAll = false
                let isFilterAllVal = ''
                this.filters.forEach(item => {
                    if (item.column == 'all') {
                        isFilterAll = true
                        isFilterAllVal = item.value.trim()
                        return
                    }
                })

                // 过滤所有字段
                if (isFilterAll) {
                    if (isFilterAllVal.trim().length) {
                        this.data = this.originalData.filter(item => {
                            let isIn = false
                            for (let i in this.filterColumns) {
                                if (this.filterColumns[i].value != 'all') {
                                    if (String(item[this.filterColumns[i].value]).indexOf(isFilterAllVal) != -1) {
                                        isIn = true
                                        break
                                    }
                                }
                            }
                            return isIn
                        })
                    } else {
                        this.data = this.originalData
                    }
                } else {
                    this.data = this.originalData.filter(item => {
                        let isIn = true
                        for (let i = 0; i < this.filters.length; i++) {
                            let val = String(item[this.filters[i].column]).toLowerCase()
                            let keyword = this.filters[i].value.trim().toLowerCase()
                            if (this.filters[i].column == 'max_guest_num') {
                                if (this.filters[i].value) {
                                    let arr = this.filters[i].value.split('/')
                                    let begin = arr[0]
                                    let end = arr[1]
                                    if (parseInt(val) < parseInt(begin) || parseInt(val) > parseInt(end)) {
                                        isIn = false
                                    }
                                }

                            } else if (this.filters[i].column.indexOf('checkin_ratio') != -1) {
                                if (this.filters[i].value) {
                                    let arr = this.filters[i].value.split('/')
                                    let begin = arr[0]
                                    let end = arr[1]
                                    if (parseFloat(val) < parseFloat(begin) / 100 || parseFloat(val) > parseFloat(end) / 100) {
                                        isIn = false
                                    }
                                }
                            } else {
                                if (val.indexOf(keyword) == -1) {
                                    isIn = false
                                }
                            }
                        }
                        return isIn
                    })
                }
            }
        }
    }
</script>

<style scoped>

</style>